package com.lis.scf.service.impl;

import com.lis.scf.common.enums.BusinessExceptionEnum;
import com.lis.scf.common.dto.request.CompanyInfoDTO;
import com.lis.scf.common.dto.request.CompanyQueryDTO;
import com.lis.scf.common.dto.response.CompanyDetailDTO;
import com.lis.scf.common.dto.PageResultDTO;
import com.lis.scf.entity.Company;
//import com.lis.scf.entity.EnterpriseInfo;
import com.lis.scf.entity.EnterpriseInfo;
import com.lis.scf.entity.EnterpriseRegistration;
import com.lis.scf.entity.User;
import com.lis.scf.exception.BusinessException;
import com.lis.scf.repository.CompanyRepository;
import com.lis.scf.repository.EnterpriseInfoRepository;
import com.lis.scf.repository.EnterpriseRegistrationRepository;
import com.lis.scf.repository.UserRepository;
import com.lis.scf.service.CompanyService;
import javax.persistence.criteria.Predicate;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 企业服务实现类
 */
@Service
@RequiredArgsConstructor
public class CompanyServiceImpl implements CompanyService {

    private final CompanyRepository companyRepository;
    private final EnterpriseInfoRepository enterpriseInfoRepository;
    private final EnterpriseRegistrationRepository registrationRepository;
    private final UserRepository userRepository;

    /**
     * 获取企业详情
     */
    @Override
    @Transactional(readOnly = true)
    public CompanyDetailDTO getCompanyDetail(Long companyId) {
        // 1. 查询企业主表
        Company company = companyRepository.findById(companyId)
                .orElseThrow(() -> new BusinessException(BusinessExceptionEnum.COMPANY_NOT_FOUND));

        // 2. 查询注册状态
        EnterpriseRegistration registration = registrationRepository
                .findTopByCompanyCompanyIdOrderByStepCompleteTimeDesc(companyId)
                .orElse(new EnterpriseRegistration());


        // 3. 查询企业详细信息
        EnterpriseInfo enterpriseInfo = enterpriseInfoRepository.findByCompanyId(companyId)
                .orElse(new EnterpriseInfo());

        // 4. 转换为DTO
        return convertToDetailDTO(company, registration, enterpriseInfo);
//        return convertToDetailDTO(company, registration);

//        return null;
    }

    /**
     * 完善企业信息
     */
//    @Override
    @Transactional
    public void completeCompanyInfo(Long companyId, CompanyInfoDTO infoDTO) {
        // 1. 验证企业存在
        Company company = companyRepository.findById(companyId)
                .orElseThrow(() -> new BusinessException(BusinessExceptionEnum.COMPANY_NOT_FOUND));

        // 2. 保存或更新企业详细信息
        EnterpriseInfo enterpriseInfo = enterpriseInfoRepository.findByCompanyId(companyId)
                .orElse(new EnterpriseInfo());

        enterpriseInfo.setCompany(company);
        enterpriseInfo.setBusinessAddress(infoDTO.getBusinessAddress());
        enterpriseInfo.setBusinessScope(infoDTO.getBusinessScope());
        enterpriseInfo.setAssetScale(infoDTO.getAssetScale());
        enterpriseInfo.setOperatorIdNumber(infoDTO.getOperatorIdNumber());
        enterpriseInfo.setOperatorMobile(infoDTO.getOperatorMobile());
        enterpriseInfo.setUpdateTime(LocalDateTime.now());

        enterpriseInfoRepository.save(enterpriseInfo);

        // 3. 更新企业主表的基本信息
        company.setBusinessAddress(infoDTO.getBusinessAddress());
        company.setBusinessScope(infoDTO.getBusinessScope());
        company.setAssetScale(infoDTO.getAssetScale());
        companyRepository.save(company);
    }

    /**
     * 分页查询企业列表
     */
    @Override
    @Transactional(readOnly = true)
    public PageResultDTO<CompanyDetailDTO> queryCompanyList(CompanyQueryDTO queryDTO) {

        // 1. 构建动态查询条件
        Specification<Company> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 企业名称模糊查询
            if (queryDTO.getCompanyName() != null && !queryDTO.getCompanyName().isEmpty()) {
                predicates.add(cb.like(root.get("companyName"), "%" + queryDTO.getCompanyName() + "%"));
            }

            // 企业类型筛选
            if (queryDTO.getCompanyType() != null) {
                predicates.add(cb.equal(root.get("companyType"), queryDTO.getCompanyType()));
            }

            return cb.and(predicates.toArray(new Predicate[0]));
        };

        // 2. 分页查询
        Pageable pageable = PageRequest.of(
                queryDTO.getPageNum() - 1,  // JPA页码从0开始
                queryDTO.getPageSize()
        );
        Page<Company> companyPage = companyRepository.findAll(spec, pageable);

        // 3. 转换为DTO并封装分页结果
        List<CompanyDetailDTO> dtoList = companyPage.getContent().stream()
                .map(company -> {
                    EnterpriseRegistration registration = registrationRepository
                            .findTopByCompanyCompanyIdOrderByStepCompleteTimeDesc(company.getCompanyId())
                            .orElse(new EnterpriseRegistration());
                    EnterpriseInfo info = enterpriseInfoRepository.findByCompanyId(company.getCompanyId())
                            .orElse(new EnterpriseInfo());
                    return convertToDetailDTO(company, registration, info);
                })
                .collect(Collectors.toList());

        return new PageResultDTO<>(
                queryDTO.getPageNum(),
                queryDTO.getPageSize(),
                companyPage.getTotalElements(),
                dtoList
        );
    }

    /**
     * 更新企业状态
     */
    @Override
    @Transactional
    public void updateCompanyStatus(Long companyId, Boolean isActive) {
        Company company = companyRepository.findById(companyId)
                .orElseThrow(() -> new BusinessException(BusinessExceptionEnum.COMPANY_NOT_FOUND));

        company.setIsActive(isActive);
        companyRepository.save(company);
    }

    /**
     * 获取当前用户所属企业信息
     */
    @Override
    @Transactional(readOnly = true)
    public CompanyDetailDTO getCurrentUserCompany(String username) {
        // 1. 查询用户信息
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new BusinessException(BusinessExceptionEnum.USER_NOT_FOUND));

        // 2. 查询企业信息
        return getCompanyDetail(user.getCompany().getCompanyId());
    }

    /**
     * 转换为企业详情DTO
     */
//    private CompanyDetailDTO convertToDetailDTO(Company company,
//                                                EnterpriseRegistration registration,
//                                                EnterpriseInfo info) {
//        CompanyDetailDTO dto = new CompanyDetailDTO();
//        dto.setCompanyId(company.getId());
//        dto.setCompanyName(company.getCompanyName());
//        dto.setUnifiedCreditCode(company.getUnifiedCreditCode());
//        dto.setCompanyType(company.getCompanyType());
//        dto.setBusinessAddress(info.getBusinessAddress() != null ? info.getBusinessAddress() : company.getBusinessAddress());
//        dto.setBusinessScope(info.getBusinessScope() != null ? info.getBusinessScope() : company.getBusinessScope());
//        dto.setAssetScale(info.getAssetScale() != null ? info.getAssetScale() : company.getAssetScale());
//        dto.setCreateTime(company.getCreateTime());
//        dto.setUpdateTime(info.getUpdateTime() != null ? info.getUpdateTime() : company.getCreateTime());
//        dto.setRegistrationStatus(registration.getRegistrationStatus());
//        dto.setIsActive(company.getIsActive());
//        return dto;
//    }

    /**
     * 将企业主信息、注册流程信息、补充信息整合转换为企业详情DTO
     * @param company 企业主实体（company表，必传）
     * @param registration 企业注册流程实体（enterprise_registration表，可为null）
     * @param info 企业补充信息实体（enterprise_info表，可为null）
     * @return 完整的企业详情DTO
     */
    private CompanyDetailDTO convertToDetailDTO(
            Company company,
            EnterpriseRegistration registration,
            EnterpriseInfo info) {
        // 1. 初始化DTO
        CompanyDetailDTO detailDTO = new CompanyDetailDTO();

        // 2. 映射企业主表核心信息（必传，无需判空）
        detailDTO.setCompanyId(company.getCompanyId());
        detailDTO.setCompanyName(company.getCompanyName());
        detailDTO.setUnifiedCreditCode(company.getUnifiedCreditCode());
        detailDTO.setCompanyType(company.getCompanyType());
//        detailDTO.setIsActive(company.getIsActive());
        detailDTO.setCreateTime(company.getCreateTime());
//        detailDTO.setLegalPerson(company.getLegalPerson()); // 法定代表人
//        detailDTO.setContactPhone(company.getContactPhone()); // 联系电1话

        // 3. 映射企业注册流程信息（可能为null，需判空）
        if (registration != null) {
            detailDTO.setRegistrationStep(registration.getRegistrationStep()); // 当前注册步骤（如1:基本信息, 2:实名认证）
//            detailDTO.setStepCompleteTime(registration.getStepCompleteTime()); // 步骤完成时间
//            detailDTO.setRegistrationStatus(registration.getStatus()); // 注册状态（如"进行中"、"已完成"）
//            detailDTO.setAuditor(registration.getAuditor()); // 审核人（如有）
//            detailDTO.setAuditOpinion(registration.getAuditOpinion()); // 审核意见
        }

//        // 4. 映射企业补充信息（可能为null，需判空）
//        if (info != null) {
//            detailDTO.setBusinessAddress(info.getBusinessAddress());
//            detailDTO.setBusinessScope(info.getBusinessScope());
//            detailDTO.setAssetScale(info.getAssetScale());
//            detailDTO.setOperatorIdNumber(info.getOperatorIdNumber()); // 操作员证件号（可脱敏）
//            detailDTO.setOperatorMobile(info.getOperatorMobile());
//            detailDTO.setUpdateTime(info.getUpdateTime()); // 信息更新时间
//            detailDTO.setBankAccount(info.getBankAccount()); // 银行账户信息
//        }
//
//        // 5. 计算衍生字段（可选）
//        // 注册进度百分比（假设总步骤为3步）
//        if (registration != null && registration.getStep() != null) {
//            int totalSteps = 3;
//            int currentStep = registration.getStep();
//            detailDTO.setRegistrationProgress((currentStep * 100) / totalSteps); // 进度百分比
//        }
//
//        // 企业存续天数
//        if (company.getCreateTime() != null) {
//            long days = ChronoUnit.DAYS.between(company.getCreateTime(), LocalDateTime.now());
//            detailDTO.setSurvivalDays((int) days);
//        }

        return detailDTO;
    }

}
